package com.caiwangdai.app.ui

import android.Manifest
import android.content.res.Configuration
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v4.app.Fragment
import android.view.View
import com.caiwangdai.app.AppData
import com.caiwangdai.app.BuildConfig
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.LatestApkB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.doubleClick
import com.caiwangdai.app.extension.showMissingPermissionDialog
import com.caiwangdai.app.extension.toast
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.ui.home.borrow.BorrowFragment
import com.caiwangdai.app.ui.home.me.MeFragment
import com.caiwangdai.app.ui.home.repay.BorrowRecordListFragment
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.content_main_bottom_bar.*
import www.weimu.io.silentupdate.SilentUpdate

class MainActivity : BaseActivity() {
    override fun getLayoutResID() = R.layout.activity_main

    private var curIndex: Int = 0
    private val fragments = arrayListOf<Fragment>()
    private val bomImages = arrayListOf<View>()//底部的控件
    private val bomtv = arrayListOf<View>()


    override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
        super.onSaveInstanceState(outState, outPersistentState)
        outState?.putInt("currentIndex", curIndex)  //保存当前显示的fragment的索引
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initFragment(savedInstanceState)
        initBottom()
        setCurrentFragment(curIndex)
        checkPermission()
    }


    private fun initFragment(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {

            curIndex = savedInstanceState.getInt("currentIndex")//异常推出前所在的fragment
            //获取到已经存在的fragment,并且存放到集合中
            val manager = supportFragmentManager
            val borrow = manager.findFragmentByTag(BorrowFragment::class.java.name)
            borrow?.apply {
                fragments.add(0, this)
            }
            val borrowList = manager.findFragmentByTag(BorrowRecordListFragment::class.java.name)
            borrowList?.apply {
                fragments.add(1, this)
            }
            val me = manager.findFragmentByTag(MeFragment::class.java.name)
            me?.apply {
                fragments.add(2, this)
            }
        } else {

            fragments.add(BorrowFragment.newInstance())
            fragments.add(BorrowRecordListFragment.newInstance(BorrowRecordListFragment.POSITION_VIEWPAGE))
            fragments.add(MeFragment.newInstance())
        }
    }


    private fun initBottom() {
        bomImages.add(main_iv_home)
        bomImages.add(main_iv_invest)
        bomImages.add(main_iv_me)
        bomtv.add(main_tv_home)
        bomtv.add(main_tv_invest)
        bomtv.add(main_tv_me)
    }

    //xml已经设置
    fun onBottomCLick(view: View) {
        val index = (view.tag as String).toInt()
        setCurrentFragment(index, (index != 0))
    }


    private fun setCurrentFragment(index: Int, needLogin: Boolean = false) {
        if (needLogin && isNeedLogin()) return
        setCurrentFragment(index)
    }

    fun setCurrentFragment(index: Int) {
        curIndex = index

        for (i in bomImages.indices) {
            bomImages[i].isActivated = (i == index)
            bomtv[i].isActivated = (i == index)
        }
        val transaction = supportFragmentManager.beginTransaction()

        transaction.setCustomAnimations(R.anim.abc_popup_enter, R.anim.abc_popup_exit)
        //隐藏所有fragment
        for (fragment in fragments) {
            transaction.hide(fragment)
        }
        val currentFragment = fragments[index]
        if (currentFragment.isAdded) {
            transaction.show(currentFragment)
        } else {
            //Logger.e(fragments.get(index).getClass().getName());
            transaction.add(R.id.fragment_container, currentFragment, fragments[index].javaClass.name)
            transaction.show(currentFragment)
        }
        transaction.commitAllowingStateLoss()
    }

    override fun onBackPressed() {
        doubleClick({ AppData.exitApp() }, { toast("再按一次退出程序") })
    }

    //登录成功后
    override fun onLoginSuccess() {
        setCurrentFragment(curIndex)
    }

    //登录取消后
    override fun onLoginCancel() {
        curIndex = 0
        setCurrentFragment(0)
    }

    //检查权限
    private fun checkPermission() {
        RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    if (granted!!)
                        getLatestApk()
                    else
                        showMissingPermissionDialog("没有此权限，APP将无法正常更新APP")

                }
    }

    //获取最新的apk下载地址
    private fun getLatestApk() {
        RetrofitHome.getHomeApi()
                .getLatestApk()
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<LatestApkB>(this) {
                    override fun isShowProgressBar() = false
                    override fun onSuccess(value: NormalResponseB<LatestApkB>) {
                        super.onSuccess(value)
                        val info = value.data?.ver_info
                        val latestVersion = info?.current_ver
                        val downloadUrl = info?.download_url
                        val currentVersion = BuildConfig.VERSION_NAME
                        //判断版本号
                        if (latestVersion!! > currentVersion)
                            SilentUpdate.update(downloadUrl!!, latestVersion)
                    }

                })
    }

    //横竖屏切换时只会调用此方法
    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
    }

}